#include "xlcomm/net/rpc/rpc_codec.h"

#include "xlcomm/net/buffer.h"
#include "xlcomm/net/tcp_connection.h"

namespace xlcomm {
namespace net {

RpcCodec::RpcCodec() {}

void RpcCodec::OnMessage(const TcpConnectionPtr& conn, Buffer* buff,
                         Timestamp recv_time) {
  LOG_TRACE << "----";
  while (static_cast<int>(buff->ReadableBytes()) >= kHeaderSize) {
    int len = buff->PeekInt32ToHost();
    if (static_cast<int>(buff->ReadableBytes()) - kHeaderSize < len) break;

    buff->ReadInt32ToHost();
    RpcMeta meta;
    meta.DeserialFromBuffer(*buff);
    if (rpc_cb_) {
      LOG_TRACE << "----";
      rpc_cb_(conn, meta);
    }
  }
}

void RpcCodec::Send(const TcpConnectionPtr& conn, const RpcMeta& meta) {
  Buffer buff;
  meta.SerialToBuffer(buff);
  // TODO: 校验码
  buff.PrependInt32ToNet(static_cast<int>(buff.ReadableBytes()));
  conn->Send(&buff);
}

}  // namespace net
}  // namespace xlcomm